<!--
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-22 09:15:25
-->
<template>
  <div>
    <el-tree
      ref="treeRef"
      node-key="id"
      :data="treeDate"
      :props="defaultProps"
      show-checkbox
      default-expand-all
    />

    <div>
      <el-button type="primary" @click="setRole">确定</el-button>
      <el-button @click="cancelSetRole">返回</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { reqEditRoleList, reqSetRole } from '@/api/role'
import type { IDataChild } from '@/types/role'
import { ElMessage, type ElTree } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 树行组件列表数据
const treeDate = ref<IDataChild[]>()
// 默认配置项
const defaultProps = {
  children: 'children',
  label: 'name'
}

const treeRef = ref<InstanceType<typeof ElTree>>()

// 设置角色
const setRole = async () => {
  // 得到所有全选的id
  const checkedIds = treeRef.value?.getCheckedKeys()
  // 得到所有半选的id
  const halfCheckedIds = treeRef.value?.getHalfCheckedKeys()
  // 合并全选和半选的id， 并用逗号连接成串
  var ids = checkedIds?.concat(halfCheckedIds as []).join(',')

  const res = await reqSetRole(route.query.id as string, ids as string)

  if (res.code === 20000) {
    ElMessage.success('新增成功')
    // 跳转到角色列表
    router.replace('/acl/role/list')
  }
}

// 取消
const cancelSetRole = () => {
  // 跳转到角色列表
  router.replace('/acl/role/list')
}

// 获取菜单列表
const getPermissonList = async () => {
  const res = await reqEditRoleList(route.query.id as string)

  if (res.code === 20000) {
    treeDate.value = res.data.children
    console.log(treeDate.value)
    const checkedKeys = getCeckedKeys(treeDate.value)
    treeRef.value?.setCheckedKeys(checkedKeys)
  }
}

// 回显列表
const getCeckedKeys = (treeDate: IDataChild[], initArr: string[] = []) => {
  treeDate.forEach((item) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id as string)
    } else if (item.children) {
      getCeckedKeys(item.children as any, initArr)
    }
  })

  return initArr
}

onMounted(() => {
  getPermissonList()
})
</script>

<script lang="ts">
export default {
  name: 'RoleAuth'
}
</script>

<style lang="scss" scoped></style>
